package com.example.Blog.controller;

import com.example.Blog.model.Article;
import com.example.Blog.model.User;
import com.example.Blog.service.ArticleService;
import com.example.Blog.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class UserController {
    final UserService userService;
    final ArticleService articleService;
    final int pageSize = 2;

    public UserController(UserService userService, ArticleService articleService) {
        this.userService = userService;
        this.articleService = articleService;
    }

    @GetMapping("/login")
    public String login(HttpServletRequest httpServletRequest, Model model) {
        if (httpServletRequest.getSession().getAttribute("loginUser") != null) {
            Page<Article> articleList = this.articleService.findAllByPageIndex(0, 20);
            model.addAttribute("articles", articleList);
            return "index";
        } else return "user/login";
    }

    @GetMapping("/register")
    public String register() {
        return "user/register";
    }

    @PostMapping("/login")
    @ResponseBody
    public String login(@ModelAttribute User user, HttpServletRequest httpServletRequest) {
        // origin error: param(@RequestBody User user) // @RequestBody表示方法期望接受一个JSON
        // 但是前端页面声明了application/x-www-form-urlencoded，浏览器将会报错415
        User destinationUser = this.userService.login(user);
        if (destinationUser != null) {
            httpServletRequest.getSession().setAttribute("loginUser", destinationUser);
            return "successful";
        } else return "wrong_password";
    }

    @PostMapping("/register")
    public String register(@ModelAttribute User user, @RequestParam("avatar") MultipartFile avatar,
                           HttpServletRequest httpServletRequest, Model model) {
        user.setUserNickname(user.getUserAccount());
        this.userService.savePhoto(user, avatar);
        try {
            user = this.userService.register(user);
            httpServletRequest.getSession().setAttribute("loginUser", user);
            Page<Article> articleList = this.articleService.findAllByPageIndex(1, 20);
            model.addAttribute("articles", articleList);
        } catch (DataIntegrityViolationException e) {
            // TODO: 2023/11/24 可能不会做这个，因为最好的办法是在用户输入用户名时就校验。
        }
        return "index";
    }

    @GetMapping("/delete")
    public void delete(@RequestParam int uid) {
        userService.delete(uid);
    }

    @GetMapping("/follow")
    public void follow(@RequestParam int uid) {
        userService.follow(uid);
    }

    @GetMapping
    public User viewUser(@RequestParam int uid) {
        return this.userService.findUser(uid);
    }

    @GetMapping("/findUser")
    @ResponseBody
    public User viewUser(String userAccount) {
        return this.userService.findUserByAccount(userAccount);
    }

    @GetMapping("/verifyUser")
    @ResponseBody
    public boolean verifyUser(@RequestParam String userAccount) {
        return this.userService.verifyValidAccount(userAccount);
    }

    @GetMapping("/logOut")
    public String logOut(HttpServletRequest httpServletRequest) {
        httpServletRequest.getSession().setAttribute("loginUser", null);
        return "user/login";
    }

    @GetMapping("/index")
    public String home(Model model) {
        Page<Article> articleList = this.articleService.findAllByPageIndex(0, pageSize);
        model.addAttribute("articles", articleList);
        return "index";
    }

    @GetMapping("/profile")
    public String profile(@RequestParam int userId, Model model, @RequestParam int pageIndex) {
        Page<Article> articleListPages = this.articleService.findAllByArticleBelongTo(pageIndex, pageSize, userId);
        int prePage = articleListPages.previousOrFirstPageable().getPageNumber();
        int nextPage = articleListPages.nextOrLastPageable().getPageNumber();
        model.addAttribute("prePage", prePage);
        model.addAttribute("nextPage", nextPage);
        model.addAttribute("articles", articleListPages);
        return "user/profile";
    }

    @PostMapping("/updateProfile")
    public String updateProfile(User user, HttpServletRequest httpServletRequest) {
        int userId = user.getUserId();
        String newUserPassword = user.getUserPassword();
        String newUserNickname = user.getUserNickname();
        if (!"".equals(newUserPassword)) {
            this.userService.updateUserPassword(newUserPassword, userId);
        }
        if (!"".equals(newUserNickname)) {
            this.userService.updateUserNickname(newUserNickname, userId);
            User updatedUser = this.userService.findUser(userId);
            httpServletRequest.getSession().setAttribute("loginUser", updatedUser);
        }
        return "redirect:/profile?pageIndex=0&userId=" + userId;
    }
}
